package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminMapper;
import com.heima.admin.service.AdminService;
import com.heima.common.exception.CustomException;
import com.heima.model.common.admin.dtos.AdUserDto;
import com.heima.model.common.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;

import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, AdUser> implements AdminService{
    /**
     * 登陆
     *
     * @param adUserDto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        //1.参数校验
        if (adUserDto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.正常登录
        //2.1校验用户名
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDto.getName()));
        if (adUser == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2.2校验密码加盐加密
        String passWord = MD5Utils.encode(adUserDto.getPassword() + adUser.getSalt());
        if (!passWord.equals(adUser.getPassword())){
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //2.3判断状态
        if (adUser.getStatus() == 0 || adUser.getStatus() == 1){
            throw new CustomException(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //3.基于当前用户的id生成token令牌
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",adUser);
        return ResponseResult.okResult(map);
    }
}
